﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Entities;
using Entities.ThuQuy;
using BLL.ThuQuy;
using System.Collections;

namespace WindowsForms.ThuQuy
{
    public partial class FormChiTietHoaDon : Form
    {
        public static string mahd;
        public static string tennhanvien;
        int macthd;
    

        public FormChiTietHoaDon()
        {
            InitializeComponent();
            dataGridViewcthd.AutoGenerateColumns = false;
            //string dataSource = FormHoaDon.mahoadon;

            //LoadLvChiTietHoaDon(ChiTietHoaDon.Objects.Find(p => p.MaHD == dataSource).ToList());
        }

        private void FormChiTietHoaDon_Load(object sender, EventArgs e)
        {


            lbnoidung.Text = "    Mã Hóa Đơn: " + mahd.ToUpper();
            dataGridViewcthd.DataSource = ChiTietHoaDon.Objects.Find(x => x.MaHD == mahd).ToList();
            tennhanvien = FormMain.tkhoan.TenNhanVien;
        }

        private void LoadLvChiTietHoaDon(List<ChiTietHoaDon> list)
        {
            //lvCTHD.Items.Clear();
            //foreach (var item in list)
            //{
            //    ListViewItem lvitem = new ListViewItem(item.MaHD);
            //    lvitem.SubItems.Add(item.MaCTHD.ToString());
            //    lvitem.SubItems.Add(item.LoaiChi.ToString());
            //    lvitem.SubItems.Add(item.VatPham);
            //    lvitem.SubItems.Add(item.SoLuong.ToString());
            //    lvitem.SubItems.Add(item.ThanhTien.ToString());
            //    lvitem.SubItems.Add(item.NoiDung);
            //}
        }
 
 
        private void btnIn_Click(object sender, EventArgs e)
        {
            PrintPreviewDialog printDialog = new PrintPreviewDialog();
            printDialog.Document = printDocument1;
            //printDialog.UseEXDialog = true;


            //Get the document

            if (DialogResult.OK == printDialog.ShowDialog())
            {

                printDocument1.DocumentName = "Test Page Print";
                printDocument1.Print();

            }

        }
        int iCellHeight, iHeaderHeight;
        double iTotalWidth;
        bool bNewPage, bFirstPage;
        public StringFormat strFormat;
        public ArrayList arrColumnWidths = new ArrayList();
        public ArrayList arrColumnLefts = new ArrayList();
        public int iCount;
        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            int iRow = 0;


            try
            {
                //Set the left margin
                int iLeftMargin = e.MarginBounds.Left - 25;
                //Set the top margin
                int iTopMargin = e.MarginBounds.Top;
                //Whether more pages have to print or not
                bool bMorePagesToPrint = false;
                int iTmpWidth = 0;
                int iCount = 0;

                //For the first page to print set the cell width and header height
                if (bFirstPage)
                {
                    //foreach (DataGridViewColumn GridCol in dataGridViewtk.Columns)
                    //{
                    //    iTmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /
                    //        (double)iTotalWidth * (double)iTotalWidth *
                    //        ((double)e.MarginBounds.Width / (double)iTotalWidth))));

                    //    iHeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,
                    //        GridCol.InheritedStyle.Font, iTmpWidth).Height) + 11;

                    //    // Save width and height of headers
                    //    arrColumnLefts.Add(iLeftMargin);
                    //    arrColumnWidths.Add(iTmpWidth);
                    //    iLeftMargin += iTmpWidth;
                    //}
                    for (int k = 0; k < dataGridViewcthd.ColumnCount; k++)
                    {


                        iTmpWidth = (int)(Math.Floor((double)((double)dataGridViewcthd.Columns[k].Width + 15 /
                        (double)iTotalWidth * (double)iTotalWidth *
                        ((double)e.MarginBounds.Width / (double)iTotalWidth))));
                        iTmpWidth = (int)(Math.Floor((double)((double)dataGridViewcthd.Columns[k].Width /
                            (double)iTotalWidth * (double)iTotalWidth *
                            ((double)e.MarginBounds.Width / (double)iTotalWidth))));

                        iHeaderHeight = (int)(e.Graphics.MeasureString(dataGridViewcthd.Columns[k].HeaderText,
                            dataGridViewcthd.Columns[k].InheritedStyle.Font, iTmpWidth).Height) + 11;

                        // Save width and height of headers
                        arrColumnLefts.Add(iLeftMargin);
                        arrColumnWidths.Add(iTmpWidth);
                        iLeftMargin += iTmpWidth;

                    }
                }

                //Loop till all the grid rows not get printed
                while (iRow <= dataGridViewcthd.Rows.Count - 1)
                {
                    DataGridViewRow GridRow = dataGridViewcthd.Rows[iRow];
                    //Set the cell height
                    iCellHeight = GridRow.Height + 10;

                    //Check whether the current page settings allows more rows to print
                    if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
                    {
                        bNewPage = true;
                        bFirstPage = false;
                        bMorePagesToPrint = true;
                        break;
                    }
                    else
                    {
                        if (bNewPage)
                        {
                            DateTime ngay = DateTime.Now;
                            //Draw Header
                            e.Graphics.DrawString("Người Lập In Hóa Đơn: " + tennhanvien + "\nNgày " + ngay.Day + " Tháng " + ngay.Month + " Năm "+ngay.Year,
                                new Font(dataGridViewcthd.Font, FontStyle.Italic),
                                Brushes.Black, e.MarginBounds.Left,
                                e.MarginBounds.Top - e.Graphics.MeasureString("Người Lập In Hóa Đơn: " + tennhanvien,
                                new Font(dataGridViewcthd.Font, FontStyle.Italic),
                                e.MarginBounds.Width).Height - 13);

                            String strDate = DateTime.Now.ToLongDateString() + " " +
                                DateTime.Now.ToShortTimeString();
                            //Draw Date
                            e.Graphics.DrawString("                       Tổng Tiền: "+TongTien(),
                                new Font(dataGridViewcthd.Font, FontStyle.Italic), Brushes.Black,
                                e.MarginBounds.Left +
                                (e.MarginBounds.Width - e.Graphics.MeasureString(strDate,
                                new Font(dataGridViewcthd.Font, FontStyle.Italic),
                                e.MarginBounds.Width).Width),
                                e.MarginBounds.Top - e.Graphics.MeasureString("Người Lập In Hóa Đơn: " + tennhanvien,
                                new Font(new Font(dataGridViewcthd.Font, FontStyle.Italic),
                                FontStyle.Bold), e.MarginBounds.Width).Height - 13);

                            //Draw Columns                 
                            iTopMargin = e.MarginBounds.Top;
                            //foreach (DataGridViewColumn GridCol in dataGridViewtk.Columns)
                            //{
                            //    e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                            //        new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                            //        (int)arrColumnWidths[iCount], iHeaderHeight));

                            //    e.Graphics.DrawRectangle(Pens.Black,
                            //        new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                            //        (int)arrColumnWidths[iCount], iHeaderHeight));

                            //    e.Graphics.DrawString(GridCol.HeaderText,
                            //        GridCol.InheritedStyle.Font,
                            //        new SolidBrush(GridCol.InheritedStyle.ForeColor),
                            //        new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
                            //        (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
                            //    iCount++;
                            //}
                            for (int l = 0; l < dataGridViewcthd.Columns.Count; l++)
                            {

                                e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                                    new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight));

                                e.Graphics.DrawRectangle(Pens.Black,
                                    new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight));

                                e.Graphics.DrawString(dataGridViewcthd.Columns[l].HeaderText,
                                    dataGridViewcthd.Columns[l].InheritedStyle.Font,
                                    new SolidBrush(dataGridViewcthd.Columns[l].InheritedStyle.ForeColor),
                                    new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
                                iCount++;

                            }
                            bNewPage = false;
                            iTopMargin += iHeaderHeight;
                        }
                        iCount = 0;
                        //Draw Columns Contents                
                        //foreach (DataGridViewCell Cel in GridRow.Cells)
                        //{
                        //    if (Cel.Value != null)
                        //    {
                        //        e.Graphics.DrawString(Cel.Value.ToString(),
                        //            Cel.InheritedStyle.Font,
                        //            new SolidBrush(Cel.InheritedStyle.ForeColor),
                        //            new RectangleF((int)arrColumnLefts[iCount],
                        //            (float)iTopMargin,
                        //            (int)arrColumnWidths[iCount], (float)iCellHeight),
                        //            strFormat);
                        //    }
                        //    //Drawing Cells Borders 
                        //    e.Graphics.DrawRectangle(Pens.Black,
                        //        new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                        //        (int)arrColumnWidths[iCount], iCellHeight));
                        //    iCount++;
                        //}
                        for (int t = 0; t < GridRow.Cells.Count; t++)
                        {

                            if (GridRow.Cells[t].Value != null)
                            {
                                e.Graphics.DrawString(GridRow.Cells[t].Value.ToString(),
                                    GridRow.Cells[t].InheritedStyle.Font,
                                    new SolidBrush(GridRow.Cells[t].InheritedStyle.ForeColor),
                                    new RectangleF((int)arrColumnLefts[iCount],
                                    (float)iTopMargin,
                                    (int)arrColumnWidths[iCount], (float)iCellHeight),
                                    strFormat);
                            }
                            //Drawing Cells Borders 
                            e.Graphics.DrawRectangle(Pens.Black,
                                new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                (int)arrColumnWidths[iCount], iCellHeight));
                            iCount++;

                        }
                    }

                    iRow++;
                    iTopMargin += iCellHeight;
                }
                //If more lines exist, print another page.
                if (bMorePagesToPrint)
                    e.HasMorePages = true;
                else
                    e.HasMorePages = false;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK,
                   MessageBoxIcon.Error);
            }

        }
        private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            try
            {
                strFormat = new StringFormat();
                strFormat.Alignment = StringAlignment.Near;
                strFormat.LineAlignment = StringAlignment.Center;
                strFormat.Trimming = StringTrimming.EllipsisCharacter;

                arrColumnLefts.Clear();
                arrColumnWidths.Clear();
                iCellHeight = 0;
                iCount = 0;
                bFirstPage = true;
                bNewPage = true;

                // Calculating Total Widths
                iTotalWidth = 0;
                //foreach (DataGridViewColumn dgvGridCol in dataGridViewtk.Columns)
                //{
                //    iTotalWidth += dgvGridCol.Width;
                //}
                for (int k = 0; k < dataGridViewcthd.Columns.Count; k++)
                {
                    iTotalWidth += dataGridViewcthd.Columns[k].Width - 12;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        private float TongTien()
        {
            List<ChiTietHoaDon> ds = ChiTietHoaDon.Objects.Find(x => x.MaHD == mahd).ToList();
            return ds.Sum(x => x.ThanhTien);
        }

  

        private void xóaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
           if(MessageBox.Show("Bạn Có Thật Sự Muốn Xóa Không","Hỏi",MessageBoxButtons.OKCancel,MessageBoxIcon.Warning)==DialogResult.OK)
           {
               if(ChiTietHoaDon.Objects.Delete(x=>x.MaCTHD==macthd))
                 {  MessageBox.Show("Xóa Thành Công");
                 dataGridViewcthd.DataSource = ChiTietHoaDon.Objects.Find(x => x.MaHD == mahd).ToList();
                 }
               else MessageBox.Show("Xóa Thất Bại");
           }
        }

        private void thoátToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

      

        private void dataGridViewcthd_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                macthd = Convert.ToInt32(dataGridViewcthd[0, e.RowIndex].Value);
                
            }
            catch (Exception)
            {
                
                 
            }
            
        }

  
      
    }
}
